import * as cloudDb from '@agconnect/database-server';
import { learning_path } from './model/learning_path';
import { user_learning } from './model/user_learning.js';
import { LearningPathResp } from './model/LearningPathResp.js';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;
  cloudDbInstance;
  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      try {
        this.cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        this.cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = this.cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async queryLearningPath(userid) {
    let pathList = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const pathQuery = cloudDb.CloudDBZoneQuery.where(learning_path).orderByAsc('id');
      const pathResp = await this.cloudDbZone.executeQuery(pathQuery);
      let pathData = pathResp.getSnapshotObjects();
      this.logger.info("query learning path success ");
      console.log('pathData=>', pathData.length);
      if (pathData.length > 0) {
        let learnedPathIds = [];
        if (userid) {
          learnedPathIds = await this.queryLearnedPathIds(userid);
        }
        for (let i = 0; i < pathData.length; i++) {
          let dataQ: learning_path = pathData[i];
          pathList.push(new LearningPathResp(
            dataQ.getId(),
            dataQ.getTag(),
            dataQ.getTitle(),
            dataQ.getZone(),
            dataQ.getUrl(),
            dataQ.getBrief(),
            learnedPathIds.indexOf(dataQ.getId()) !== -1,
          ))
        }
      }
    } catch (error) {
      this.logger.info("query learn path error " + error);
    } finally {
      return pathList;
    }
  }

  async queryLearnedPathIds(userid) {
    let learnedPathIds = [];
    try {
      const userLearningQuery = cloudDb.CloudDBZoneQuery.where(user_learning)
      userLearningQuery.equalTo('user_id', userid)
      const userLearningResp = await this.cloudDbZone.executeQuery(userLearningQuery);
      let userLearningData = userLearningResp.getSnapshotObjects();
      this.logger.info("query user_learning success ");
      console.log('userLearningData=>', userLearningData.length);
      for (let index = 0; index < userLearningData.length; index++) {
        const element: user_learning = userLearningData[index];
        learnedPathIds.push(element.getPath_id());
      }
      return learnedPathIds;
    } catch (error) {
      this.logger.info("query learnedPathIds error " + error);
    }
  }
}
